package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @author 衷岚
 * @version 1.0
 * 设置全局唯一ID --> long类型 64比特位， 1位（符号位0），31位（时间戳--可存69年的），32位（序列号）
 */
@Component
public class RedisIDWorker {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final long BEGIN_TIMESTAMP =  1743984000L;
    private static final int  COUNT_BITS = 32;

    public long nextID(String keyPrefix){

        /**
         * 1.生成时间戳
         * 2.生成序列号
         * 3.拼接时间戳和序列号
         */
        LocalDateTime now = LocalDateTime.now();
        long second = now.toEpochSecond(ZoneOffset.UTC);
        //生成时间戳
        long timestamp = second-BEGIN_TIMESTAMP;
        //生成序列号
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy:MM:dd");
        String date = formatter.format(now);
        Long count = stringRedisTemplate.opsForValue().increment("icr:"+keyPrefix + ":" + date );

        return timestamp <<COUNT_BITS | count;



    }
    public static void main(String[] args) {
        LocalDateTime time = LocalDateTime.of(2025,04,07,0,0,0);
        long epochSecond = time.toEpochSecond(ZoneOffset.UTC);
        System.out.println(epochSecond);
        RedisIDWorker redisIDWorker = new RedisIDWorker();
        long voucherID = redisIDWorker.nextID("voucher");
        System.out.println(voucherID);

    }


}

